﻿using System;
using System.Configuration;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using xxpl.DNS;
using xxpl.HTTP;

namespace xxpl
{
    class Program
    {
        static readonly RequestDispacther dispactcher = new RequestDispacther();

        static void Main(string[] args)
        {
            ServicePointManager.DefaultConnectionLimit = 32;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidationCallback1;

            DnsHelper.Init();

            HttpListener listener = new HttpListener();

            listener.Prefixes.Add(string.Format("http://+:{0}/", ConfigurationManager.AppSettings["Port"]));

            listener.Start();

            Console.WriteLine("Listening...");

            listener.BeginGetContext(OnGetContext, listener);

            Console.ReadLine();
        }

        private static void OnGetContext(IAsyncResult ar)
        {
            HttpListener listener = (HttpListener)ar.AsyncState;
            HttpListenerContext context = listener.EndGetContext(ar);

            dispactcher.DispatchRequest(context);

            listener.BeginGetContext(OnGetContext, listener);
        }

        static readonly Regex regex = new Regex("CN=[^\\.]+\\.google\\.com", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        private static bool RemoteCertificateValidationCallback1(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            if (sslpolicyerrors == SslPolicyErrors.None)
                return true;
            if (sslpolicyerrors == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                return regex.IsMatch(certificate.Subject);
            }
            return false;
        }
    }
}
